package it.tukano.swingdeco;

import it.tukano.reflection.MethodExt;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
import javax.swing.AbstractButton;
import javax.swing.JComponent;

/**
 * Utilities used by the deco extensions
 * @author pgi
 */
public class ExtUtilities {

    /**
     * Scales the font of a component
     * @param c the component
     * @param factor the scale factor
     */
    public static void scaleFont(Component c, double factor) {
        Font font = c.getFont();
        font = font.deriveFont(font.getSize() * (float) factor);
        c.setFont(font);
    }

    /**
     * Binds the action event of a button to the execution of a runnable
     * @param button the button
     * @param task the task to execute
     */
    public static void onActionPerformed(AbstractButton button, final Runnable task) {
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                task.run();
            }
        });
    }

    /**
     * Set the tool tip text for a component getting it from a resource bundle.
     * @param component the component
     * @param bundleId the resource bundle id
     * @param key the key of the resource
     */
    public static void setToolTipText(JComponent component, String bundleId, String key) {
        String tip = String.format("[missing %s %s]", bundleId, key);
        ResourceBundle bundle = ResourceBundle.getBundle(bundleId);
        if(bundle != null && bundle.containsKey(key)) {
            tip = bundle.getString(key);
        }
        component.setToolTipText(tip);
    }

    /**
     * Invokes the public setText method of the given component with the value of a resource bundle key
     * @param component the component
     * @param bundleId the id of the resource bundle
     * @param key the key of the text in the bundle
     */
    public static void setText(Object component, String bundleId, String key) {
        MethodExt setText = new MethodExt(component, "setText", String.class);
        ResourceBundle bundle = ResourceBundle.getBundle(bundleId);
        if(bundle != null && setText != null && bundle.containsKey(key)) {
            setText.invoke(bundle.getString(key));
        }
    }
    
    public static void center(Component parent, Component child) {
        Dimension parentSize = parent.getSize();
        Point parentLocation = parent.getLocation();
        Dimension childSize = child.getSize();
        int x = parentLocation.x + (parentSize.width - childSize.width) / 2;
        int y = parentLocation.y + (parentSize.height - childSize.height) / 2;
        child.setLocation(x, y);
    }

    /**
     * Instance initializer
     */
    ExtUtilities() {
    }
}
